//
//  ChineseGroupingUtil.swift
//  LogisticsCargoOwner
//
//  Created by safiri on 2020/8/5.
//  Copyright © 2020 qiluys. All rights reserved.
//

import Foundation

public struct ChineseGroup {
    
    /// 字符串值
    public var chinese = ""
    
    /// 拼音
    public var pinyin = ""
    
}

public class ChineseGroupUtil {
    
    /// 汉字数组转为 ChineseGroup 数组，并根据拼音排序
    /// - Parameters:
    ///   - array: 汉字数组
    ///   - isForSurname: 是否有多音字姓氏
    /// - Returns: ChineseGroup 数组
    public static func parseAndSort(chineseArray: [String], isForSurname: Bool = false) -> [ChineseGroup] {
        var result: [ChineseGroup] = []
        for chineseString in chineseArray {
            var chineseGroup = ChineseGroup()
            chineseGroup.chinese = chineseString.trimmingCharacters(in: .whitespacesAndNewlines)
            chineseGroup.pinyin = chineseGroup.chinese.pinyinForSort(isForSurname: isForSurname, withYindiao: false)
            result.append(chineseGroup)
        }
        //按照拼音首字母排序 
        result.sort { $0.pinyin < $1.pinyin }
        return result
    }
    
    
    /// 汉字数组提取 首字母 数组，并根据首字母排序
    /// - Parameters:
    ///   - chineseArray: 汉字数组
    ///   - isForSurname: 是否有多音字姓氏
    /// - Returns: 首字母 数组
    public static func parseAndSortPinyinFirstLetter(chineseArray: [String], isForSurname: Bool = false) -> [String] {
        let originArray = parseAndSort(chineseArray: chineseArray)
        var result: [String] = []
        var temp = ""
        for chineseGroup in originArray {
            let pinyinFirstLetter = String(chineseGroup.pinyin.first ?? "#")
            if temp != pinyinFirstLetter { //不同
                result.append(pinyinFirstLetter)
                temp = pinyinFirstLetter
            }
        }
        return result
    }
    
    /// 汉字数组提取汉字，放在对应首字母数组的二维数组中
    /// - Parameters:
    ///   - chineseArray: 汉字数组
    ///   - isForSurname: 是否有多音字姓氏
    /// - Returns: 二维数组
    public static func parseAndSort2DArrayForPinyinFirstLetter(chineseArray: [String], isForSurname: Bool = false) -> [[String]] {
        let originArray = parseAndSort(chineseArray: chineseArray)
        var result: [[String]] = []
        
        var temp = "" //分组数组
        for chineseGroup in originArray {
            let pinyinFirstLetter = String(chineseGroup.pinyin.first ?? "#")
            let value = chineseGroup.chinese
            if temp != pinyinFirstLetter {
                var item: [String] = []
                item.append(value)
                result.append(item)
                temp = pinyinFirstLetter
            }else {
                result[result.endIndex-1].append(value)
            }
        }
        return result
    }
}

